﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
using OnlineEducation.Controllers;
using OnlineEducation.Helpers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineEducation.Extensions
{
    /// <summary>
    /// 只允许一个用户名登录一个在线用户，不允许多个相同的用户名同时在线。
    /// 结合redis，判断用户key 在redis 是否存在，如存在，则踢掉前一个用户。
    /// </summary>
    public class SingleLoginActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.AttributeRouteInfo != null && filterContext.ActionDescriptor.AttributeRouteInfo.Template.StartsWith("api/"))
            {
                //nothing to do.....
            }
            else if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (filterContext.RouteData.Values["controller"].ToString() != "Account")
                {
                    IDistributedCache distributedCache = (IDistributedCache)filterContext.HttpContext.RequestServices.GetService(typeof(IDistributedCache));

                    Hashtable singleOnlineUser = distributedCache.Get<Hashtable>("__SingleOnlineUser");

                    // 判断当前SessionID是否存在
                    if (singleOnlineUser != null && singleOnlineUser.ContainsKey(filterContext.HttpContext.User.Identity.Name))
                    {
                        if (!singleOnlineUser[filterContext.HttpContext.User.Identity.Name].Equals(HttpContextHelper.Current.Session.Get<string>("ID")))
                        {
                            if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                            {

                                filterContext.HttpContext.Response.StatusCode = 401;
                                filterContext.Result = new UnauthorizedResult();

                            }
                            else
                            {
                                filterContext.HttpContext.Response.StatusCode = 401;
                                filterContext.Result = new RedirectResult("/Account/Login"); //new ContentResult() { Content = "<script>alert('您的账号已在别处登陆。');window.location.href='/Account/Login';</script>" };
                            }
                        }
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }



    }
}
